package top.jolyoulu.streaming

import org.apache.spark.SparkConf
import org.apache.spark.streaming.dstream.{DStream, ReceiverInputDStream}
import org.apache.spark.streaming.{Seconds, StreamingContext}

/**
 * @Author: JolyouLu
 * @Date: 2024/5/19 15:07
 * @Description
 */
object Spark01_SparkStreaming_State_Window {
  def main(args: Array[String]): Unit = {
    val sparkConf: SparkConf = new SparkConf().setMaster("local[*]").setAppName("SparkStreaming")
    val ssc = new StreamingContext(sparkConf, Seconds(3))

    val lines: ReceiverInputDStream[String] = ssc.socketTextStream("192.168.88.100", 9999)
    val wordToOne: DStream[(String, Int)] = lines.map((_, 1))
    //窗口范围应该是采集周期的倍数
    //窗口滑动步长默认是一个采集周期，可以手动设置防止数据重复处理
    val windowDS: DStream[(String, Int)] = wordToOne.window(Seconds(6),Seconds(6))
    val wordToCount: DStream[(String, Int)] = windowDS.reduceByKey(_ + _)
    wordToCount.print()

    ssc.start()
    ssc.awaitTermination()
  }
}
